import { PlayerBase } from './PlayerBase.js'
import { useWebsocketStore } from '@/stores/websocket.js'
import { useUserStore } from '@/stores/user.js'

/**
 * 自己控制的玩家类，继承自PlayerBase
 * 负责管理玩家输入和特定行为
 */
export class MyPlayer extends PlayerBase {
    constructor(gameMap, info) {
        super(gameMap, info)
    }

    // 接收玩家输入
    add_listening_events() {
        if (this.isDead) {
            return
        }
        const canvas = this.gameMap.ctx.canvas
        canvas.addEventListener('mousedown', (e) => {
            const rect = canvas.getBoundingClientRect()
            const clickX = e.clientX - rect.left
            const clickY = e.clientY - rect.top
            // 右键
            if (e.button === 2) {
                this.move_to(clickX, clickY)

                // 联机对战中，需要向后端发送移动事件
                if (this.gameMap.constructor.name === 'PvPGameMap') {
                    const websocketStore = useWebsocketStore()
                    const userStore = useUserStore()

                    // 发送移动事件
                    if (websocketStore.socket.readyState === WebSocket.OPEN) {
                        // 计算相对于canvas的比例坐标 (0-1范围)
                        const relativeTx = clickX / this.gameMap.width
                        const relativeTy = clickY / this.gameMap.height
                        const relativeX = this.info.x / this.gameMap.width
                        const relativeY = this.info.y / this.gameMap.height

                        websocketStore.socket.send(
                            JSON.stringify({
                                event: 'move',
                                userId: userStore.id,
                                roomId: websocketStore.pk.roomId,
                                tx: relativeTx,
                                ty: relativeTy,
                                x: relativeX,
                                y: relativeY,
                            })
                        )
                    } else {
                        console.log('socket未打开')
                    }
                }
            } else if (e.button === 0) {
                if (this.currentSkill && this.skills[this.currentSkill]) {
                    // 使用技能
                    const result = this.skills[this.currentSkill].cast(clickX, clickY)

                    // 检查技能释放是否成功
                    const success =
                        result === true || (typeof result === 'object' && result.success)

                    if (success) {
                        console.log('使用技能' + this.currentSkill + '成功')

                        // 联机对战中，向后端发送技能使用事件
                        if (this.gameMap.constructor.name === 'PvPGameMap') {
                            // 如果是闪现，传递实际闪现坐标
                            if (this.currentSkill === 'flash' && typeof result === 'object') {
                                this.sendSkillEvent(
                                    this.currentSkill,
                                    clickX,
                                    clickY,
                                    result.newX,
                                    result.newY
                                )
                            } else {
                                this.sendSkillEvent(this.currentSkill, clickX, clickY)
                            }
                        }
                    } else {
                        console.log('使用技能' + this.currentSkill + '失败')
                    }
                }
            }
        })
        window.addEventListener('keydown', (e) => {
            if (this.isDead) {
                return
            }
            const key = e.key.toUpperCase()
            for (const skillName in this.skills) {
                if (key === this.skills[skillName].skillKey.toUpperCase()) {
                    if (skillName === 'heal') {
                        // 治疗技能直接触发
                        const success = this.skills[skillName].cast()
                        // 联机对战中，向后端发送治疗事件
                        if (success && this.gameMap.constructor.name === 'PvPGameMap') {
                            this.sendSkillEvent(skillName)
                        }
                    } else {
                        // 其他技能需要选择目标
                        this.currentSkill = this.skills[skillName].skillName
                    }
                    break
                }
            }
        })
        window.addEventListener('keyup', (e) => {
            if (this.isDead) {
                return
            }
            const key = e.key.toUpperCase()
            for (const skillName in this.skills) {
                if (
                    key === this.skills[skillName].skillKey.toUpperCase() &&
                    this.currentSkill === this.skills[skillName].skillName
                ) {
                    this.currentSkill = null
                    break
                }
            }
        })
    }

    // 发送技能事件到后端
    sendSkillEvent(skillName, targetX = null, targetY = null, actualX = null, actualY = null) {
        const websocketStore = useWebsocketStore()
        const userStore = useUserStore()

        if (websocketStore.socket.readyState !== WebSocket.OPEN) {
            console.log('socket未打开，无法发送技能事件')
            return
        }

        // 基础事件数据
        const eventData = {
            userId: userStore.id,
            roomId: websocketStore.pk.roomId,
        }

        // 根据技能类型设置不同的事件
        switch (skillName) {
            case 'fireball':
                eventData.event = 'shoot_fireball'
                break
            case 'flash':
                eventData.event = 'flash'
                break
            case 'heal':
                eventData.event = 'heal'
                break
            default:
                console.log('未知技能类型：' + skillName)
                return
        }

        // 如果有目标坐标，添加到事件数据中（适用于火球和闪现）
        if (targetX !== null && targetY !== null) {
            // 发送相对坐标
            eventData.tx = targetX / this.gameMap.width
            eventData.ty = targetY / this.gameMap.height
            eventData.x = this.info.x / this.gameMap.width
            eventData.y = this.info.y / this.gameMap.height

            // 对于闪现技能，发送实际落点坐标
            if (skillName === 'flash' && actualX !== null && actualY !== null) {
                eventData.actualX = actualX / this.gameMap.width
                eventData.actualY = actualY / this.gameMap.height
            }
        }

        // 发送事件到后端
        websocketStore.socket.send(JSON.stringify(eventData))
        console.log('发送技能事件：', eventData)
    }

    start() {
        this.add_listening_events()
    }

    // 为自己的玩家绘制技能图标
    draw_skill_icon() {
        if (!this.skills) {
            return
        }
        const scale = this.height
        let baseX = 1.2
        let y = 0.9
        let r = 0.04

        // 渲染每个技能图标
        let skillIndex = 0
        for (const skillKey in this.skills) {
            const skill = this.skills[skillKey]
            const x = baseX + skillIndex * 0.12
            // 绘制技能图标和冷却
            skill.draw_skill_icon(x, y, r, scale)

            skillIndex++
        }
    }
}
